package com.eedi.framework.mail.service;

import cn.hutool.core.util.StrUtil;
import com.google.common.annotations.VisibleForTesting;
import com.eedi.framework.common.enums.UserTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import com.eedi.framework.mail.dal.dataobject.SysMailTemplateDO;
import com.eedi.framework.mail.dal.dataobject.SysMailAccountDO;

import javax.annotation.Resource;
import java.util.Map;

import static com.eedi.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.eedi.framework.mail.enums.SysMailErrorCodeConstants.*;


/**
 * 邮箱发送 Service 实现类
 *
 * @author zybourn
 * @since 2022-03-21
 */
@Service
@Validated
@Slf4j
public class SysMailSendServiceImpl implements SysMailSendService {

//    @Resource
//    private AdminUserService adminUserService;
//    @Resource
//    private MemberService memberService;

    @Resource
    private SysMailAccountService sysMailAccountService;
    @Resource
    private SysMailTemplateService sysMailTemplateService;

    @Resource
    private SysMailLogService sysMailLogService;
//    @Resource
//    private MailProducer mailProducer;

    @Override
    public Long sendSingleMailToAdmin(String mail, String userId,
                                      String templateCode, Map<String, Object> templateParams) {
        // 如果 mail 为空，则加载用户编号对应的邮箱
//        if (StrUtil.isEmpty(mail)) {
//            AdminUserDO user = adminUserService.getUser(userId);
//            if (user != null) {
//                mail = user.getEmail();
//            }
//        }
        // 执行发送
        return sendSingleMail(mail, userId, UserTypeEnum.MEMBER_SYS, templateCode, templateParams);
    }

    @Override
    public Long sendSingleMailToMember(String mail, String userId,
                                       String templateCode, Map<String, Object> templateParams) {
        // 如果 mail 为空，则加载用户编号对应的邮箱
//        if (StrUtil.isEmpty(mail)) {
//            mail = memberService.getMemberUserEmail(userId);
//        }
        // 执行发送
        return sendSingleMail(mail, userId, UserTypeEnum.MEMBER_SYS, templateCode, templateParams);
    }

    @Override
    public Long sendSingleMail(String mail, String userId, UserTypeEnum userType,
                               String templateCode, Map<String, Object> templateParams) {
        // 校验邮箱模版是否合法
//        MailTemplateDO template = validateMailTemplate(templateCode);
        // 校验邮箱账号是否合法
//        MailAccountDO account = validateMailAccount(template.getAccountId());
//
//        // 校验邮箱是否存在
//        mail = validateMail(mail);
//        validateTemplateParams(template, templateParams);
//
//        // 创建发送日志。如果模板被禁用，则不发送短信，只记录日志
//        Boolean isSend = CommonStatusEnum.ENABLE.getCode().equals(template.getStatus());
//        String title = mailTemplateService.formatMailTemplateContent(template.getTitle(), templateParams);
//        String content = mailTemplateService.formatMailTemplateContent(template.getContent(), templateParams);
//        Long sendLogId = mailLogService.createMailLog(userId, userType, mail,
//                account, template, content, templateParams, isSend);
//        // 发送 MQ 消息，异步执行发送短信
//        if (isSend) {
//            mailProducer.sendMailSendMessage(sendLogId, mail, account.getId(),
//                    template.getNickname(), title, content);
//        }
//        return sendLogId;
        return null;
    }

//    @Override
//    public void doSendMail(MailSendMessage message) {
//        // 1. 创建发送账号
//        MailAccountDO account = validateMailAccount(message.getAccountId());
//        MailAccount mailAccount  = MailAccountConvert.INSTANCE.convert(account, message.getNickname());
//        // 2. 发送邮件
//        try {
//            String messageId = MailUtil.send(mailAccount, message.getMail(),
//                    message.getTitle(), message.getContent(),true);
//            // 3. 更新结果（成功）
//            mailLogService.updateMailSendResult(message.getLogId(), messageId, null);
//        } catch (Exception e) {
//            // 3. 更新结果（异常）
//            mailLogService.updateMailSendResult(message.getLogId(), null, e);
//        }
//    }

//    @VisibleForTesting
//    MailTemplateDO validateMailTemplate(String templateCode) {
//        // 获得邮件模板。考虑到效率，从缓存中获取
//        MailTemplateDO template = mailTemplateService.getMailTemplateByCodeFromCache(templateCode);
//        // 邮件模板不存在
//        if (template == null) {
//            throw exception(MAIL_TEMPLATE_NOT_EXISTS);
//        }
//        return template;
//    }

    @VisibleForTesting
    SysMailAccountDO validateMailAccount(String accountId) {
        // 获得邮箱账号。考虑到效率，从缓存中获取
        SysMailAccountDO account = sysMailAccountService.getMailAccountFromCache(accountId);
        // 邮箱账号不存在
        if (account == null) {
            throw exception(SYS_MAIL_ACCOUNT_NOT_EXISTS);
        }
        return account;
    }

    @VisibleForTesting
    String validateMail(String mail) {
        if (StrUtil.isEmpty(mail)) {
            throw exception(SYS_MAIL_SEND_MAIL_NOT_EXISTS);
        }
        return mail;
    }

    /**
     * 校验邮件参数是否确实
     *
     * @param template 邮箱模板
     * @param templateParams 参数列表
     */
    @VisibleForTesting
    void validateTemplateParams(SysMailTemplateDO template, Map<String, Object> templateParams) {
        template.getParams().forEach(key -> {
            Object value = templateParams.get(key);
            if (value == null) {
                throw exception(SYS_MAIL_SEND_TEMPLATE_PARAM_MISS, key);
            }
        });
    }

}
